package com.heima.example.chat.server.handler;

import com.heima.example.chat.message.RpcRequestMessage;
import com.heima.example.chat.message.RpcResponseMessage;
import com.heima.example.chat.server.service.ServicesFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * @author ZhengDp
 * @Date 2023/7/7 11:35
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    /*
    * 通过反射调用 对应的方法
    * */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) throws Exception {
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        try {
            // 获取接口对应的对象
            Object service = ServicesFactory.getService(Class.forName(msg.getInterfaceName()));
            Method method = service.getClass().getMethod(msg.getMethodName(), msg.getParameterTypes());
            Object result = method.invoke(service, msg.getParameterValue());
            responseMessage.setReturnValue(result);
        }catch (Exception e) {
            log.error("Rpc方法调用失败 " ,e);
            responseMessage.setExceptionValue(new Exception("远程调用出错:" + e.getCause().getMessage() ));
        }
        ctx.writeAndFlush(responseMessage);
    }
}
